<template>
  <div>
    <div
      style="
        padding: 16px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
      "
    >
      <el-text size="large" style="padding-bottom: 16px">
        <b>值班天数统计</b>
      </el-text>
      <el-form inline size="small">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="起始日期（含）"
            end-placeholder="截止日期（含）"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            <span>统计</span>
          </el-button>
          <el-button type="primary" @click="handleOpenHolidayDialog">
            <el-icon><Pointer /></el-icon>
            <span>节日</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      v-model="showHolidayDialog"
      title="编辑节日信息"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      width="360px"
    >
      <el-form>
        <el-form-item>
          <el-input
            v-model="holidayDialogContent"
            size="small"
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 20 }"
            resize="none"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSaveHolidays">
            <span>保存</span>
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      v-model="showProgressDialog"
      append-to-body
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="240px"
    >
      <div class="loading-indicator">
        <div style="font-size: 24px; padding-bottom: 24px">处理中</div>
        <div style="font-size: 72px">
          <el-icon class="is-loading"><Loading /></el-icon>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, h, onMounted } from "vue";
import { ElNotification, ElMessageBox } from "element-plus";
import dayjs from "dayjs";

import fetchWorkingDays from "./fetchWorkingDays.js";
import querySeatHours from "./querySeatHours.js";
import requestHolidays from "./requestHolidays.js";

const emits = defineEmits(["resolved"]);

const dateRange = ref([new Date(), new Date()]);
const rawData = ref(null);
const declarationData = ref(null);
const mixData = ref(null);
const workData = ref(null);
const holidays = ref(["2024-02-01", "2024-02-02"]);
const showProgressDialog = ref(false);
const handleQuery = () => {
  showProgressDialog.value = true;
  requestHolidays()
    .then((res) => {
      holidays.value = res;
      console.log("requestHolidays", res);
      querySeatHours(dateRange.value)
        .then((response) => {
          setTimeout(() => {
            rawData.value = response.data;
            declarationData.value = response.declarations;
            mixData.value = response.mixture;
            workData.value = fetchWorkingDays(
              mixData.value,
              dateRange.value,
              holidays.value
            );
            showProgressDialog.value = false;
            ElNotification({
              type: "info",
              title: "统计结果",
              message: h("div", null, [
                h("div", null, "检索 " + rawData.value.length + " 条打卡记录"),
                h(
                  "div",
                  null,
                  "另有 " + declarationData.value.length + " 条申报记录"
                ),
                h("div", null, "产生 " + workData.value.length + " 人值班记录"),
              ]),
            });
            if (declarationData.value.length > 0) {
              alertDeclarations(declarationData.value);
            }
            emits("resolved", {
              data: workData.value,
              raw: rawData.value,
              range: dateRange.value,
              declarations: declarationData.value,
            });
          }, 100);
        })
        .catch((error) => {});
    })
    .catch((error) => {});
};

const showHolidayDialog = ref(false);
const holidayDialogContent = ref("");
const handleOpenHolidayDialog = () => {
  holidayDialogContent.value = holidays.value.join("\n");
  showHolidayDialog.value = true;
};
const handleSaveHolidays = () => {
  let content = holidayDialogContent.value.split("\n");
  requestHolidays(content)
    .then((res) => {
      holidays.value = content;
      console.log("requestHolidays", res);
      if (res) {
        showHolidayDialog.value = false;
      }
    })
    .catch((error) => {
      //
    });
};

const alertDeclarations = (declarations) => {
  const css = {
    table: { textAlign: "center" },
    thead: { fontWeight: "bolder" },
    tbody: {},
    tr: { padding: "4px 0" },
    td: { padding: "0 8px" },
    root: {
      width: "50vw",
      minWidth: "480px",
      maxWidth: "540px",
      minHeight: "120px",
      maxHeight: "calc(100vh - 200px)",
      overflow: "auto",
    },
  };
  ElMessageBox({
    title: "申报记录",
    message: h("table", { style: css.table }, [
      h("thead", { style: css.thead }, [
        h("tr", { style: css.tr }, [
          h("td", { style: css.td }, "姓名"),
          h("td", { style: css.td }, "开始时间"),
          h("td", { style: css.td }, "结束时间"),
          h("td", { style: css.td }, "备注"),
        ]),
      ]),
      h(
        "tbody",
        { style: css.tbody },
        declarations.map((cell) =>
          h("tr", { style: css.tr }, [
            h("td", { style: css.td }, cell.userName),
            h(
              "td",
              { style: css.td },
              dayjs(cell.startTime).format("MM/DD HH:mm")
            ),
            h(
              "td",
              { style: css.td },
              dayjs(cell.endTime).format("MM/DD HH:mm")
            ),
            h("td", { style: css.td }, cell.remark),
          ])
        )
      ),
    ]),
    customStyle: css.root,
  });
};

onMounted(() => {
  requestHolidays()
    .then((res) => {
      holidays.value = res;
      console.log("requestHolidays", res);
    })
    .catch((error) => {
      //
    });
});
</script>

<style scoped>
.loading-indicator {
  width: 100%;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>
